package cn.wangzg.mymusic;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<Music> musicList;
    private ListAdapter myListAdapter;
    private ListView listView;
    private SeekBar musicSeekBar;

    //三个按钮
    private ImageView btnPlay;
    private Button btnNext;
    private Button btnPrevious;

    //控制台显示的内容
    private TextView title;
    private TextView artist;
    private TextView durationTime;
    private ImageView conImage;


    //自定义Binder对象 用于调用服务中的方法
    private MyBinderInterface myBinder;
    //自定义服务连接对象
    private MyServiceConnection conn;
    //是否正在播放
    private boolean isPlaying = false;

    private BroadcastMain receiver;
    //内部类，实现BroadcastReceiver
    public class BroadcastMain extends BroadcastReceiver {
        //必须要重载的方法，用来监听是否有广播发送
        @Override
        public void onReceive(Context context, Intent intent) {

            title.setText(intent.getStringExtra("title"));
            artist.setText(intent.getStringExtra("artist"));
            int pos = intent.getIntExtra("pic",0);

            Bitmap bitmap = getImage(pos);
            if(bitmap != null){
                conImage.setImageBitmap(bitmap);
            }
        }
    }

    //定义服务连接
    private class MyServiceConnection implements ServiceConnection{
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (MyBinderInterface)service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    //更新播放状态
    private void updateState() {
        int index = myBinder.getCurrentIndex();
        myListAdapter.setFocusItemPos(index);
//        title.setText(musicList.get(index).getTitle());
//        artist.setText(musicList.get(index).getArtist());
//        durationTime.setText(MusicUtils.formatTime(musicList.get(index).getDuration()));
//
//        Bitmap bitmap = getImage(musicList.get(index).getAlbumId());
//        if (bitmap != null){
//            conImage.setImageBitmap(bitmap);
//        }else {
//            conImage.setImageResource(R.drawable.music);
//        }

        btnPlay.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.pause));
        isPlaying = true;
    }

    private Bitmap getImage(int id) {
        int album_id = id;
        String albumArt = getAlbumArt(album_id);
        Bitmap bm = null;
        if (albumArt != null) {
            bm = BitmapFactory.decodeFile(albumArt);
            return bm;
        }
        return null;
    }

    private String getAlbumArt(int album_id) {
        String mUriAlbums = "content://media/external/audio/albums";
        String[] projection = new String[] { "album_art" };

        Cursor cur = getContentResolver().query( Uri.parse(mUriAlbums + "/" + Integer.toString(album_id)), projection, null, null, null);
        String album_art = null;
        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
            cur.moveToNext();
            album_art = cur.getString(0);
        }
        cur.close();
        cur = null;
        return album_art;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        musicList = new ArrayList<>();
        //获取音乐列表
        musicList = MusicUtils.getMusic(getApplicationContext());
        //获取视图
        initView();

        registerForContextMenu(listView);
        conn = new MyServiceConnection();
        //绑定服务
        bindService(new Intent(this,MusicService.class),conn, Context.BIND_AUTO_CREATE);
    }

    //初始化视图
    private void initView(){
        btnPlay = findViewById(R.id.play_btn);
        btnNext = findViewById(R.id.next_btn);
        btnPrevious = findViewById(R.id.pre_btn);
        conImage = findViewById(R.id.im_image);

        musicSeekBar = (SeekBar)findViewById(R.id.seek_music);

        title = findViewById(R.id.textView1);
        artist = findViewById(R.id.textView2);
        durationTime = findViewById(R.id.textView3);
        listView = findViewById(R.id.list);
        myListAdapter = new ListAdapter(MainActivity.this,musicList);
        listView.setAdapter(myListAdapter);
        setListener();
    }

    private void setListener() {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                myBinder.setCurrentIndex(position);
                myBinder.Play();

                myListAdapter.setFocusItemPos(position);
                updateState();
            }
        });

        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPlaying == true){
                    btnPlay.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.play));
                    isPlaying = false;
                    myBinder.Pause();
                    return;
                }
                if (isPlaying == false){
                    if (myBinder.getCurrentIndex() == -1){
                        myBinder.setCurrentIndex(0);
                        myListAdapter.setFocusItemPos(0);
                        myBinder.Play();
                        updateState();
                    }
                    btnPlay.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.pause));
                    isPlaying = true;
                    myBinder.Resume();
                }
            }
        });

        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myBinder.PlayNext();
                updateState();
            }
        });

        btnPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myBinder.PlayPrev();
                updateState();
            }
        });
    }
}